package com.jushu.storbox;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.actions.NodeAction;
import com.jushu.storbox.actions.ThumbnailAction;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.IntentConstant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LinkAccessCodeUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.DateTimePickerDialog;
import com.jushu.storbox.view.viewImpl.SlipButton;
import com.jushu.storbox.view.viewImpl.SlipButton.OnChangedListener;
import com.huawei.sharedrive.sdk.android.modelV2.request.LinkCreateRequestV2;
import com.huawei.sharedrive.sdk.android.modelV3.response.LinkInfoV3;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class EditLinkActivity extends BaseTitleActivity {
	private final static String LOG_TAG = EditLinkActivity.class.toString();
	private FileFolderInfo mInfo;
	private LinkInfoV3 linkInfo;
	private Boolean isComplexAccessCode;
	private String iconPath;
	private ImageView itemIcon;
	private TextView itemName;
	private TextView itemDate;
	private TextView linkUrl;
	private TextView linkValiStartEdtSel;
	private EditText linkValiStartEdt;
	private TextView linkValidEndEdtSel;
	private EditText linkValidEndEdt;
	private EditText linkCodeEdt;
	private ImageView linkCodeEdtImg;
	private SlipButton linkCodeSlip;
	private boolean linkCodeEnabled;
	private SlipButton linkExpiredSlip;
	private boolean linkExpireEnabled;
	private RelativeLayout linkCodeLayout;
	private RelativeLayout dateFromLayout;
	private RelativeLayout dateToLayout;
	private int action;
	private CheckBox upload;
	private CheckBox download;
	private CheckBox browser;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.add_link);

		setCurrentTitle(this.getString(R.string.link));
		currentTitle.setText(R.string.button_back);
		returnIcon.setVisibility(View.GONE);

		// init title
		switchTypeOne();
		rightOperation.setVisibility(View.VISIBLE);
		rightIcon.setVisibility(View.GONE);
		rightOperation.setText(R.string.lock_save_password);
		rightOperation.setOnClickListener(onSaveListener);

		// init content view
		dateFromLayout = (RelativeLayout) findViewById(R.id.dateFromLayout);
		dateToLayout = (RelativeLayout) findViewById(R.id.dateToLayout);
		linkCodeLayout = (RelativeLayout) findViewById(R.id.formLayout);
		linkCodeSlip = (SlipButton) findViewById(R.id.enableLinkCode);
		linkCodeSlip.SetOnChangedListener(linkCodeSlipListenser);
		linkExpiredSlip = (SlipButton) findViewById(R.id.enableValid);
		linkExpiredSlip.SetOnChangedListener(linkDateSlipListenser);
		itemIcon = (ImageView) findViewById(R.id.item_type_img);
		itemName = (TextView) findViewById(R.id.item_name_text);
		itemDate = (TextView) findViewById(R.id.item_date_text);
		linkUrl = (TextView) findViewById(R.id.linkUrl);
		linkValiStartEdtSel = (TextView) findViewById(R.id.linkValiStartEdtSel);
		linkValiStartEdt = (EditText) findViewById(R.id.linkValiStartEdt);
		linkValidEndEdtSel = (TextView) findViewById(R.id.linkValidEndEdtSel);
		linkValidEndEdt = (EditText) findViewById(R.id.linkValidEndEdt);
		linkCodeEdt = (EditText) findViewById(R.id.linkCodeEdt);
		linkCodeEdtImg = (ImageView) findViewById(R.id.linkCodeEdtImg);
		
		upload = (CheckBox) findViewById(R.id.upload);
		download = (CheckBox) findViewById(R.id.download);
		browser = (CheckBox) findViewById(R.id.broswer);
		upload.setOnCheckedChangeListener(uploadListener);
		download.setOnCheckedChangeListener(downloadListener);
		browser.setOnCheckedChangeListener(browserListener);
		
		linkValiStartEdtSel.setOnClickListener(startViladListener);
		linkValidEndEdtSel.setOnClickListener(endViladListener);
		linkCodeEdtImg.setOnClickListener(refreshCodeListener);
		
		ActivityTaskManager.getInstance().putActivity(LOG_TAG, getContext());

		fillLinkInfo();
	}
	
	OnCheckedChangeListener uploadListener = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean checked) {
			if (checked){
				if(browser.isChecked()){
					download.setChecked(true);
				}else if(download.isChecked()){
					browser.setChecked(true);
				}
			}
		}
	};
	OnCheckedChangeListener downloadListener = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean checked) {
			if (checked){
				browser.setChecked(true);
			}else{
				if(upload.isChecked()){
					browser.setChecked(false);
				}
			}
		}
	};
	OnCheckedChangeListener browserListener = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean checked) {
			if(checked){
				if(upload.isChecked()){
					if(!download.isChecked()){
						download.setChecked(true);
					}
				}
			}else{
				download.setChecked(false);
			}
		}
	};

	private void fillLinkInfo() {
		Intent intent = getIntent();
		action = Integer.parseInt(intent.getAction());
		Bundle lBundle = intent.getExtras();
		mInfo = (FileFolderInfo) lBundle.getSerializable("FileFolderInfo");
		linkInfo = (LinkInfoV3) lBundle.getSerializable("LinkInfo");
		isComplexAccessCode = (Boolean) lBundle
				.getSerializable("LinkConfigInfo");

		SharedPreferences settings = getSharedPreferences(
				ClientConfig.settings, MODE_APPEND);
		String address = settings.getString(ClientConfig.SERVER_ADDRESS, "");

		if (address.trim().equals("")) {
			address = ClientConfig.SERVICEADD;
		}
		StringBuffer tmp = new StringBuffer(address);
		tmp.append("/").append("p").append("/").append(linkInfo.getId());
		linkUrl.setText(tmp.toString());
		
		//access set
		String role = linkInfo.getRole();
		if(StringUtil.isNotBlank(role)){
			if(role.equals(Constant.LINK_ROLE_UPLOADER)){
				upload.setChecked(true);
			}else if(role.equals(Constant.LINK_ROLE_UPLOAD_VIEWER)){
				upload.setChecked(true);
				browser.setChecked(true);
				download.setChecked(true);
			}else if(role.equals(Constant.LINK_ROLE_PREVIEW)){
				browser.setChecked(true);
			}if(role.equals(Constant.LINK_ROLE_VIEW)){
				browser.setChecked(true);
				download.setChecked(true);
			}
		}
		
		String plainAccessCode = linkInfo.getPlainAccessCode();
		Long effectiveAt = linkInfo.getEffectiveAt();
        Long expireAt = linkInfo.getExpireAt();
        if (StringUtil.isNotBlank(plainAccessCode)){
        	linkCodeSlip.setCheck(true);
        	linkCodeLayout.setVisibility(View.VISIBLE);
        	linkCodeEdt.setText(plainAccessCode);
        	linkCodeEnabled = true;
        }
        if (effectiveAt != null){
        	linkExpireEnabled =true;
        	linkExpiredSlip.setCheck(true);
        	dateFromLayout.setVisibility(View.VISIBLE);
        	dateToLayout.setVisibility(View.VISIBLE);
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        	linkValiStartEdt.setText(sdf.format(new Date(effectiveAt)));
        	if(expireAt != null){
        		linkValidEndEdt.setText(sdf.format(new Date(expireAt)));
        	}
        }
        
		if(isComplexAccessCode){
			linkCodeEdt.setFocusable(false);
			linkCodeEdt.setFocusableInTouchMode(false);
		}else{
			linkCodeEdtImg.setVisibility(View.GONE);
			linkCodeEdt.setFocusable(true);
			linkCodeEdt.setFocusableInTouchMode(true);
		}
		
		if (mInfo != null) {
			itemName.setText(mInfo.getName());
			itemDate.setText(formatDate());
			itemIcon.setImageResource(getTypeImgeID());
			if(mInfo.getType() == FileType.FOLDER_TYPE_VALUE){
				upload.setVisibility(View.VISIBLE);
			}
		}
	}

	private OnClickListener onSaveListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Activity activity = EditLinkActivity.this;
			if(!download.isChecked() && !browser.isChecked() && !upload.isChecked()){
				Toast.makeText(activity, activity.getString(R.string.link_access_empty), Toast.LENGTH_SHORT).show();
				return;
			}
			if(linkCodeEnabled){
    			if(StringUtil.isBlank(linkCodeEdt.getText().toString())){
    				Toast.makeText(activity, activity.getString(R.string.access_code_not_empty), Toast.LENGTH_SHORT).show();
    				return;
    			}
    			if(!isComplexAccessCode && !LinkAccessCodeUtil.isValidAccessCode(linkCodeEdt.getText().toString())){
    				Toast.makeText(activity, activity.getString(R.string.access_code_invalid), Toast.LENGTH_SHORT).show();
        			return;
    			}
    		}else{
    			linkCodeEdt.setText("");
    		}
    		if(linkExpireEnabled){
    			if(StringUtil.isBlank(linkValiStartEdt.getText().toString())){
    				Toast.makeText(activity, activity.getString(R.string.access_begin_date_empty), Toast.LENGTH_SHORT).show();
    				return;
    			}
    			try{
    				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    				Date beginDate = sdf.parse(linkValiStartEdt.getText().toString());
    				
    				if(StringUtil.isNotBlank(linkValidEndEdt.getText().toString())){
    					Date endDate = sdf.parse(linkValidEndEdt.getText().toString());
    					if(beginDate.getTime() > endDate.getTime()){
    						Toast.makeText(activity, activity.getString(R.string.access_date_error), Toast.LENGTH_SHORT).show();
    						return;
    					}
    				}
    				
    			}catch(Exception e){
    				LogUtil.e("validate date rangle limit error");
    				Toast.makeText(activity, activity.getString(R.string.access_date_invalid), Toast.LENGTH_SHORT).show();
    				return;
    			}
    		}else{
    			linkValiStartEdt.setText("");
    			linkValidEndEdt.setText("");
    		}
    		String role = "";
    		if(upload.isChecked()){
    			if(download.isChecked()){
    				role = Constant.LINK_ROLE_UPLOAD_VIEWER;
    			}else{
    				role = Constant.LINK_ROLE_UPLOADER;
    			}
    		}else{
    			if(download.isChecked()){
        			role = Constant.LINK_ROLE_VIEW;
        		}else{
        			role = Constant.LINK_ROLE_PREVIEW;
        		}
    		}
    		
    		LinkCreateRequestV2 linkRequest = new LinkCreateRequestV2();
    		linkRequest.setRole(Constant.LINK_ROLE_VIEW);
    		linkRequest.setAccess("");
    		linkRequest.setRole(role);
    		linkRequest.setAccessCodeMode("static");
    		linkRequest.setPlainAccessCode(linkCodeEnabled ? linkCodeEdt.getText().toString() : null);
    		linkRequest.setLinkCode(linkInfo.getId());
    		if(linkExpireEnabled){
    			try{
        			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            		linkRequest.setEffectiveAt(sdf.parse(linkValiStartEdt.getText().toString()).getTime());
    				if(StringUtil.isNotBlank(linkValidEndEdt.getText().toString())){
    					linkRequest.setExpireAt(sdf.parse(linkValidEndEdt.getText().toString()).getTime());
    				}
        		}catch(Exception e){
        			LogUtil.e("set link date limit error");
        		}
    		}
    		new NodeAction().updateLink(EditLinkActivity.this, mInfo, linkRequest, msgHandler);
		}
	};
	
	private OnClickListener startViladListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			DateTimePickerDialog dateTimePicKDialog = new DateTimePickerDialog(EditLinkActivity.this);
    		dateTimePicKDialog.dateTimePicKDialog(linkValiStartEdt, 0);
		}
	};
	private OnClickListener endViladListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			DateTimePickerDialog dateTimePicKDialog = new DateTimePickerDialog(EditLinkActivity.this);
    		dateTimePicKDialog.dateTimePicKDialog(linkValidEndEdt, 0);
		}
	};
	private OnClickListener refreshCodeListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			linkCodeEdt.setText(LinkAccessCodeUtil.getAccessCode(8));;
		}
	};

	private OnChangedListener linkCodeSlipListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean checkState) {
			if (checkState) {
				linkCodeEnabled = true;
				linkCodeLayout.setVisibility(View.VISIBLE);
				if(isComplexAccessCode){
					linkCodeEdtImg.setVisibility(View.VISIBLE);
					
					linkCodeEdt.setFocusable(false);
					linkCodeEdt.setFocusableInTouchMode(false);
					
					if(StringUtil.isBlank(linkCodeEdt.getText().toString())){
						linkCodeEdt.setText(LinkAccessCodeUtil.getAccessCode(8));;
					}
				}else{
					linkCodeEdtImg.setVisibility(View.INVISIBLE);
					
					linkCodeEdt.setFocusable(true);
					linkCodeEdt.setFocusableInTouchMode(true);
					
				}
			} else {
				linkCodeEnabled = false;
				linkCodeLayout.setVisibility(View.GONE);
			}
		}
	};

	private OnChangedListener linkDateSlipListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean checkState) {
			if (checkState) {
				linkExpireEnabled = true;
				dateFromLayout.setVisibility(View.VISIBLE);
				dateToLayout.setVisibility(View.VISIBLE);
			} else {
				linkExpireEnabled = false;
				dateFromLayout.setVisibility(View.GONE);
				dateToLayout.setVisibility(View.GONE);
			}
		}
	};
	
	@Override
	protected void onLeftClicked(View clickView) {
		if(action == IntentConstant.LINK_CREATE_FINISH){
			new NodeAction().deleteLink(
					this, mInfo,
					linkInfo, msgHandler);
		}
		finish();
	}

	private int getTypeImgeID() {
		// LogUtil.i(TAG, "getTypeImgeID...");
		int typeImgResId = R.mipmap.default_file_icon;
		if (mInfo.getIsFile() == FileType.File.value()) {
			if (PublicTools.isFileType(mInfo.getName(), Constant.WORD_TYPE)) {
				typeImgResId = R.mipmap.doc;
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.PPT_TYPE)) {
				typeImgResId = R.mipmap.ppt;
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.IMAGE_TYPE)) {
				typeImgResId = R.mipmap.empty_pic;
				loadImagIcon();
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.RAR_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.ZIP_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.VIDEO_TYPE)) {
				typeImgResId = R.mipmap.video;
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.MUSIC_TYPE)) {
				typeImgResId = R.mipmap.music;
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.TXT_TYPE)) {
				typeImgResId = R.mipmap.txt;
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.PDF_TYPE)) {
				typeImgResId = R.mipmap.pdf;
			} else if (PublicTools.isFileType(mInfo.getName(),
					Constant.EXCEL_TYPE)) {
				typeImgResId = R.mipmap.excel;
			} else {
				typeImgResId = R.mipmap.default_file_icon;
			}
		} else {
			typeImgResId = R.mipmap.folder_im;
		}
		return typeImgResId;
	}

	private void loadImagIcon() {
		try {
			iconPath = DirectoryUtil.genThumbnailFileFullName(getBaseContext(),
					mInfo.getOwnerBy(), mInfo.getId(), mInfo.getName());
			File thumBnail2 = new File(iconPath);
			if (!thumBnail2.exists()) {
				new ThumbnailAction()
						.downloadThumbnailIcon(getBaseContext(),
								mInfo.getOwnerBy(), mInfo.getId(), iconPath,
								msgHandler);
			} else {
				Message msg_download = new Message();
				msg_download.what = MessageCode.REQUEST_THUMBNAIL_INLOCAL;
				msgHandler.sendMessage(msg_download);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(
					TAG,
					"[getTypeImgeID] fileType is image that show fail..."
							+ e.getLocalizedMessage());
		}
	}

	ClientExceptionRelateHandler msgHandler = new ClientExceptionRelateHandler() {
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MessageCode.REQUEST_THUMBNAIL_INLOCAL:
				new Thread(new Runnable() {
					public void run() {
						LogUtil.i(TAG, "thumb path: " + iconPath);
						Bitmap bmp = BitmapFactory.decodeFile(iconPath);
						ShareDriveApplication.getInstance()
								.addCloudBitmaps(bmp);
						Message message = new Message();
						message.what = UiConstant.UPDATE_TYPE_ICON;
						message.obj = bmp;
						msgHandler.sendMessage(message);
					}
				}).start();
				break;
			case MessageCode.LINK_CREATE:
				break;
			case MessageCode.LINK_UPDATE:
				Bundle lBundle = msg.getData();
				Intent resultIntent = new Intent();
				resultIntent.putExtras(lBundle);
				setResult(IntentConstant.LINK_CREATE_FINISH,resultIntent);//have select
				EditLinkActivity.this.finish();
				break;
			case UiConstant.UPDATE_TYPE_ICON:// refresh image ui
				Bitmap bmp = (Bitmap) msg.obj;
				if (null != bmp) {
					itemIcon.setImageBitmap(bmp);
				} else {
					LogUtil.e(TAG, "bitmap is null, show default img...");
				}
				break;

			case UiConstant.SHARE_ACTION_DELETE_SHARE_SHIPS_SUCCESS:
				break;

			default:
				super.handleMessage(msg);
			}
		}

		@Override
		public Context getContext() {
			return getBaseContext();
		}
	};

	private String formatDate() {
		SimpleDateFormat timeDateFormat = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm");
		return timeDateFormat.format(mInfo.getModifiedAt());
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
	}

	private EditLinkActivity getContext() {
		return EditLinkActivity.this;
	}
	
	@Override
	public void onBackPressed() {
		if(action == IntentConstant.LINK_CREATE_FINISH){
			new NodeAction().deleteLink(
					this, mInfo,
					linkInfo, msgHandler);
		}
		finish();
	}

}
